package com.jintian.smart.kernel.autoconfigure.model;

import com.jintian.smart.kernel.common.util.MethodUtil;
import com.jintian.smart.kernel.interceptor.MultiApplicationContextInterceptor;
import org.beetl.ext.spring6.BeetlSpringView;
import org.beetl.ext.spring6.BeetlSpringViewResolver;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

public class MutiContextBeetlSpringViewResolver extends BeetlSpringViewResolver {
    private final ApplicationContext applcationContext;

    public MutiContextBeetlSpringViewResolver(ApplicationContext applcationContext) {
        this.applcationContext = applcationContext;
    }

    @Override
    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        BeanFactory modelBeanFactory = MultiApplicationContextInterceptor.getCurrentBeanFactory();
        BeetlSpringView beetlView = null;
        if (modelBeanFactory == null || modelBeanFactory == this.applcationContext.getAutowireCapableBeanFactory()) {
            beetlView = (BeetlSpringView) super.buildView(viewName);
        } else {
            BeetlSpringViewResolver resolver = modelBeanFactory.getBean(BeetlSpringViewResolver.class);
            if (resolver == this) {
                beetlView = (BeetlSpringView) super.buildView(viewName);
            } else {
                beetlView = (BeetlSpringView) MethodUtil.invokeMethod(resolver, true, "buildView", viewName);
            }
        }
        return beetlView;
    }
}
